import { Dialog } from 'vant'
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

Vue.use(VueRouter)

const routes = [
    {
      path:'/',
      component: ()=>import('../views/Layout/Layout.vue'),
      children:[{
        path:'',
        redirect: '/home'
      },{
        path:'/home',
        component: () => import('../views/Home/Home.vue')
      },{
        path: '/wa',
        component: () => import('../views/wa/wa.vue'),
        meta:{requiresAuth:true}
      },{
        path: '/video',
        component: () => import('../views/Video/Video.vue'),
        meta:{requiresAuth:true}
      },{
        path: '/my',
        name: 'my',
        component: () => import('../views/My/My.vue'),
      }]
    },
    {
      path:'/login',
      name:'login',
      component: ()=>import('../views/Login/Login.vue')
    },
    {
      path:'/search',
      name:'search',
      component:()=>import('../views/Search/Search.vue')
    },
    {
      path:'/article/:articleId',
      name:'article',
      component:()=>import('../views/Article/Article.vue'),
      props:true
    },
    {
      path:'/userprofile',
      name:'userprofile',
      component:()=>import('../views/UserProfile/UserProfile.vue')
    }

]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  // 如果已登录 则直接通过
  if(store.state.user){
   return next()
  }
  // ...
  // 如果没有登录  判断是否需要登录权限
  if(to.meta.requiresAuth){
    Dialog.confirm({
      title:'访问提示',
      message:'该功能需要登录才能访问,是否去登录'
    }).then(()=>router.replace({name:'login',query:{redirect:router.currentRoute.fullPath}}))
    .catch(()=>next(false))
  }else{
    next()
  }
})

export default router
